import React, { Component } from 'react';
import { Button, } from 'tinper-bee';
import './mapModal.less';

let map, marker, geocoder;

export default class mapModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // show: props.show,
            lng: '',
            lat: '',
            address: '',
        }
    }

    componentDidMount = () => {
        window.mapJSLoaded = () => {
            this.initMap();
        }
        if (this.props.from == 'detail') {
            this.appendGaode();
        }
    }

    componentWillUnmount = () => {
        window.mapJSLoaded = undefined;
        map && map.destroy();
        map = undefined;
    }

    componentWillReceiveProps(newProps) {
    }

    shouldComponentUpdate(newProps, newState) {
        if (this.props.from == 'detail') {
            return true;
        }
        let { initLocation } = newProps;
        if (!this.props.show && newProps.show) {
            Object.assign(this.state, initLocation);
            let { lng, lat, address } = initLocation;
            if (map) {
                this.afterSelectPoint(lng, lat, address, newState);
            }
        }
        if (!map && newProps.show) {
            let _me = this;
            if (!window.AMap) {
                this.appendGaode();
            } else {
                _me.initMap(initLocation);
            }
            return true;
        } else {
            return true;
        }
    }

    appendGaode() {
        let baseUrl = 'https://webapi.amap.com/maps?v=1.4.15&key=f43864641c8b9634393e55b355bebd05&callback=mapJSLoaded';
        let jsapi = document.createElement('script');
        jsapi.charset = 'utf-8';
        jsapi.src = baseUrl;
        document.getElementsByTagName("head")[0].appendChild(jsapi);
    }

    initMap = (initLocationNew) => {
        let { initLocation } = this.props;
        if (initLocationNew) {
            initLocation = initLocationNew;
        }
        let { lng, lat, address } = initLocation;
        map = new AMap.Map('mapContainer', {
            zoom: 12,
            center: lng ? new AMap.LngLat(lng, lat) : undefined,
        });
        marker = new AMap.Marker({
            offset: new AMap.Pixel(-13, -30),
            draggable: false,
            raiseOnDrag: false,
            cursor: 'move',
            // animation: "AMAP_ANIMATION_DROP",
        });
        if (lng) {
            this.afterSelectPoint(lng, lat, address);
        }

        // marker.on('dragend', (e) => {
        // 	let { lnglat, pixel, type, target } = e;
        // 	geocoder.getAddress(lnglat, (status, result) => {
        // 		if (status == 'complete') {
        // 			// ReGeocodeResult
        // 			alert(result.regeocode.formattedAddress);
        // 		} else if (status == 'error') {
        // 			// info
        // 		} else if (status == 'no_data') {

        // 		}
        // 	});
        // });
        map.on('click', (e) => {
            let _me = this;
            let { lnglat, pixel, type, target } = e;
            marker.setMap(map);
            marker.setPosition(lnglat);
            //根据经度纬度获取位置描述
            geocoder.getAddress(lnglat, (status, result) => {
                let address = '';
                if (status == 'complete') {
                    // ReGeocodeResult
                    address = result.regeocode.formattedAddress;
                } else if (status == 'error') {
                    // info
                } else if (status == 'no_data') {
                }
                _me.setState({
                    lng: lnglat.lng,
                    lat: lnglat.lat,
                    address: address
                })
            });
        });
        //异步同时加载多个插件
        AMap.plugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.Autocomplete', 'AMap.Geocoder',], () => {
            let scale = new AMap.Scale();
            map.addControl(scale);
            let tool = new AMap.ToolBar({
                position: 'RB',
                direction: false,
                autoPosition: !lng,
            });
            map.addControl(tool);
            geocoder = new AMap.Geocoder({ radius: 100 });
            let auto = new AMap.Autocomplete({
                input: "pickerInput",
            });
            auto.on('select', (e) => {
                let poi = e.poi;
                let { location, name } = poi;
                if (!location) {
                    //根据位置描述获取经度纬度
                    geocoder.getLocation(name, (status, result) => {
                        // let address = '';
                        if (status == 'complete') {
                            // ReGeocodeResult
                            location = result.geocodes[0].location;
                        } else if (status == 'error') {
                            // info
                        } else if (status == 'no_data') {
                        }
                        this.afterSelectPoint(location.lng, location.lat, name);
                    })
                    return;
                } else {
                    this.afterSelectPoint(location.lng, location.lat, name);
                }
            })
        });
    }

    afterSelectPoint = (lng, lat, name, newState) => {
        if (lng && lat) {
            marker.setMap(map);
            marker.setPosition(new AMap.LngLat(lng, lat));
            map.setCenter(new AMap.LngLat(lng, lat));
        } else {
            marker.setMap(null);
        }
        map.setZoom(12);
        if (newState) {
            Object.assign(newState, {
                lng,
                lat,
                address: name,
            })
        } else {
            this.setState({
                lng,
                lat,
                address: name,
            });
        }
    }

    closeMapModal = () => {
        document.getElementById('pickerInput').value = '';
        this.props.onClose();

    }

    setPosition = () => {
        document.getElementById('pickerInput').value = '';
        let { lng, lat, address } = this.state;
        this.props.onClose(lng, lat, address);
    }


    render() {
        return (
            <div className="container" style={{ display: this.props.show ? 'block' : 'none' }}>
                <div className="content">
                    <div className="header-area">
                        <h4 className="title">关联地图</h4>
                        <div className="btnContainer">
                            <span title={this.state.address} id="addressText">{this.state.address}</span>
                            <Button colors='primary' className='mapSure' onClick={this.setPosition}>确认</Button>
                            <Button className='mapCancel' size="sm" onClick={this.closeMapModal}>取消</Button>
                        </div>
                    </div>
                    <div className="body-area">
                        <div id="mapContainer">
                        </div>
                        <input id="pickerInput" placeholder="输入关键字选取地点"
                            className="nc-input demo-input u-form-control"
                            autoComplete="off"
                        ></input>
                    </div>
                </div>
            </div>
        )
    }
}